﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Baidu.Sound.Asr
{
    class Program
    {
        /// <summary>  
        /// 获取本机MAC地址  
        /// </summary>  
        /// <returns>本机MAC地址</returns>  
        public static string GetMacAddress()
        {
            try
            {
                string strMac = string.Empty;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        strMac = mo["MacAddress"].ToString();
                    }
                }
                moc = null;
                mc = null;
                return strMac;
            }
            catch
            {
                return "unknown";
            }
        }

        static void Main(string[] args)
        {
            var client = new Aip.Speech.Asr(Global.GlobalConfig.APP_ID,Global.GlobalConfig.API_KEY, Global.GlobalConfig.SECRET_KEY);
            client.Timeout = 60000;  // 修改超时时间

            HttpClient HClient = new HttpClient();
            string AKRequestURL = $"https://openapi.baidu.com/oauth/2.0/token";
            string AsrInterfaceURL = $"https://vop.baidu.com/pro_api";
            List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("grant_type", "client_credentials"),
                    new KeyValuePair<string, string>("client_id", Global.GlobalConfig.API_KEY),
                    new KeyValuePair<string, string>("client_secret", Global.GlobalConfig.SECRET_KEY)
                };
            HttpResponseMessage response = HClient.PostAsync(AKRequestURL, new FormUrlEncodedContent(paraList)).Result;

            JObject res = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            string accessToken = res["access_token"].ToString();



            Stopwatch sw = new Stopwatch();

            var data = File.ReadAllBytes(@"I:\2019-04-12 百度4月\5srecord.pcm");


            //goto Json;
            //goto raw;
            int i = 0;
            while(i<20)
            {
                sw.Reset();
                sw.Start();
                var result = client.Recognize(data, "pcm", 16000);
                sw.Stop();
                Console.WriteLine(result);
                Console.WriteLine(sw.ElapsedMilliseconds);
                i++;
            }
            Console.ReadLine();


            Console.WriteLine("______");

            Json:            

            i = 0;
            while(i<20)
            {
                HClient = new HttpClient();
                //client.MaxResponseContentBufferSize = 2147483647;
                string base64 = Convert.ToBase64String(data);
                JObject json = new JObject();
                json["format"] = "pcm";
                json["rate"] = 16000;
                json["channel"] = 1;
                json["cuid"] = GetMacAddress();
                json["token"] = accessToken;
                json["len"] = data.Length;
                json["speech"] = base64;
                json["dev_pid"] = 80001;

                var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");

                sw.Restart();
                response = HClient.PostAsync(AsrInterfaceURL, content).Result;
                sw.Stop();

                JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);

                Console.WriteLine(result.ToString());

                Console.WriteLine(sw.ElapsedMilliseconds);

                i++;
            }

            Console.ReadLine();
            Console.WriteLine("______");

        raw:
            

            i = 0;
            while (i<20)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AsrInterfaceURL + $"?dev_pid=80001&cuid={GetMacAddress().Replace(":", "")}&token={accessToken}");
                request.ContentType = "audio/pcm;rate=16000";
                request.Method = "POST";

                using (Stream str = request.GetRequestStream())
                {
                    str.Write(data, 0, data.Length);
                }
                sw.Restart();
                HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
                sw.Stop();
                Stream receiveStream = resp.GetResponseStream();


                string R = new StreamReader(receiveStream).ReadToEnd();
                Console.WriteLine(R);
                Console.WriteLine(sw.ElapsedMilliseconds);
                i++;
            }

            Console.Read();
        }
    }
}
